import store from '@/store'
import { Toast } from 'vant';
import lyricParse from './lyricParse'
import requestApi from './requestApi'

console.log("%c%s", ";background:black;color:lightgreen", "player core by wl(@WANYL)")
var player = document.createElement('audio');
console.log("初始化播放器成功");

let mData = {

    lyric_time: [],
    lyric_last_state: { time: 0, row: 0 },
    /**
    * 设置播放器动作_播放
    *【特点】如果没有正在播放的，会从播放列表拉取
    */
    play(state = null) {
        if (player.src == "") {
            if (store.state.playerState.playData.songId == 0) {
                this.action_play_next();
            }
            return;
        }
        if (typeof state == "boolean") {
            if (state) {
                player.play()
                return;
            } else {
                player.pause()
                return;
            }
        }


        if (store.state.playerState.playData.music_now_play_time > 0) {
            // player.
            player.currentTime = store.state.playerState.playData.music_now_play_time;
        }
        console.log("play")
        player.play()
    },
    /**
     * 设置播放器动作_暂停
     */
    pause() {
        player.pause()
    },


    /**
     * 播放歌曲
     * @param {int} mid 
     * @param {int} time 
     * @param {bool} rightPlay 
     * @returns 
     */
    playId(mid, time = 0, rightPlay = true) {
        if (mid == 0) { debugger; return; }
        let caches_data = store.state.DataCacheMap;
        let info = caches_data.simpleData[mid];
        store.state.playerState.playData.music_title = info["title"];
        store.state.playerState.playData.music_singer = info["singer"];
        store.state.playerState.playData.songId = mid;

        // 重置歌词状态
        this.lyric_last_state.time = 0
        this.lyric_last_state.row = 0


        // console.log("正在设置播放下一首.")
        this.service_load_lyric(mid)

        // 暂停播放当前的歌曲，再进行网络请求,获取播放地址
        if (!player.paused) player.pause()

        //旧版代码，每次都需要发起xhr请求
        // 网络请求
        // requestApi.request_getPlayUrl(mid, (data) => {
        //     player.src = data["url"];
        //     player.currentTime = time;
        //     if (rightPlay) player.play();
        // });
        //新版代码，支持从缓存加载，如果缓存没有，则从网络加载。
        this.action_updatePlayInfo(mid, (url, fee) => {
            player.src = url;
            if (fee == 1) {
                Toast("收费歌曲,免费试听60s");
            }
            player.currentTime = time;
            if (rightPlay) player.play();
        });

        // player.src = data["url"];
        // player.currentTime = time;
        // if (rightPlay) player.play();


        this.action_save_to_histroy(mid);

    },
    /**
     * 将即将播放的歌曲存放到历史列表
     * @param {int} id 
     * @returns 
     */
    action_save_to_histroy(id) {
        let t;
        try {
            if (store.state.playList.playHistory["indexOf"] == null) {
                store.state.playList.playHistory = []
            }
            if (!store.state.playList.playHistory) {
                return;
            }
            t = store.state.playList.playHistory.indexOf(id)
            if (t >= 0)
                store.state.playList.playHistory.splice(t, 1);
            store.state.playList.playHistory.unshift(id);
        } catch (e) { return; }

        // store.state.playList.playHistory = new Set(store.state.playList.playHistory);

    },
    /**
     * 设置播放器动作_转到上一首
     */
    action_play_prev() {
        let now_song = store.state.playerState.playData.songId;
        let l = store.state.playList.playNowList;
        let pos = l.indexOf(now_song);
        if (pos > 0) {
            pos = (l.length + (pos - 1)) % l.length;
        } else {
            pos = l.length - 1;
        }
        let mid = l[pos];
        this.playId(mid);
    },
    /**
     * 设置播放器动作_转到下一首
     */
    action_play_next() {
        let now_song = store.state.playerState.playData.songId;
        let l = store.state.playList.playNowList;
        store.state.playerState.playData.music_now_play_time = 0;
        let pos = l.indexOf(now_song);
        if (pos >= 0) {
            pos = (pos + 1) % l.length
        } else {
            pos = 0;
        }
        let mid = l[pos];
        this.playId(mid);
    },
    /**
     * 设置当前播放器的播放进度条
     * @param {int} type 0表示通过时间调整，1表示通过歌词行数调整
     * @param {int} src 
     * @returns 
     */
    action_move_playTime(type, src) {
        let moveTime = player.currentTime;
        if (type == 0) {
            if (src <= player.duration) moveTime = src;
        } else if (type == 1) {
            moveTime = this.lyric_time[src]
        } else {
            return;
        }
        // player.currentTime=src
        player.currentTime = moveTime;
    },
    /**
     * 通过歌曲ID更新歌曲播放链接
     * 【场景】用于缓存下一首歌曲的信息
     * @param {int} id 
     */
    action_updatePlayInfo(id, callback = null) {
        let simpleData = store.state.DataCacheMap.simpleData;
        if (!simpleData[id]) return;
        let needReRun = false;
        if (callback) {//可能需要立即播放的那种
            if (simpleData[id].playUrl && simpleData[id].playUrl["expire"] > (new Date().getTime())) {//播放链接可用
                callback(simpleData[id].playUrl["url"], simpleData[id].fee);
                console.log("从缓存加载啦")
            } else {
                // 播放链接不可用，标记一下，一会儿获取到播放链接后，需要再调用一下。
                needReRun = true;
                console.log("标记需要下载歌曲信息后调用播放")
            }
        }

        if (simpleData[id].playUrl && simpleData[id].playUrl["expire"] - 10 * 60 * 1000 > (new Date().getTime())) {//如果在10分钟内都还有效，则不进行更新
            
            return;
        }

        requestApi.request_getPlayUrl(id, (data) => {
            simpleData[id].fee = data['fee'];
            let playUD = {
                url: data["url"],
                expire: (data["expi"]) * 1000 + (new Date().getTime())
            }
            simpleData[id].playUrl = playUD;
            if (needReRun) {
                setTimeout(function(){
                    callback(data['url'], simpleData[id].fee);
                },2000)
                
            }


        }, callback != null)
    },
    /**
     * 通过歌曲ID把歌词加载到当前播放器中
     * 【场景】播放后立即加载歌词
     * 【特点】支持从缓存加载
     * @param {int} id 
     */
    service_load_lyric(id) {
        let tmpData = store.state.DataCacheMap.LrcData[id]

        if (tmpData == null) {
            console.log("联网拉取歌词")

            requestApi.request_getLyric(id, (data) => {
                if (data == null) {
                    mData.lyric_time = [0]
                    store.state.playerState.playData.lrc_list = ["网络错误,歌词加载失败~"]
                } else {
                    let m = lyricParse.parseLyric(data["lrc"]["lyric"]);
                    store.state.DataCacheMap.LrcData[id] = m;
                    mData.lyric_time = m["timeList"];
                    store.state.playerState.playData.lrc_list = m.lyricList;
                }
                mData.sync_lyric_time(player.currentTime)


            });
        } else {
            console.log("离线加载歌词")
            mData.lyric_time = tmpData["timeList"];
            store.state.playerState.playData.lrc_list = tmpData.lyricList;
        }
    },
    /**
     * 同步对应时间的歌词，找到对应行号。
     * @param {int} time 当前播放时间
     * @returns 
     */
    sync_lyric_time(time) {
        // console.log("sync_lyric_time",time)
        let mRow = this.lyric_last_state.row;
        if (this.lyric_last_state.time < time) {
            // 正常更新进度
            // let mRow = this.lyric_last_state.row;
            for (let index = this.lyric_last_state.row; index < this.lyric_time.length; index++) {
                if (this.lyric_time[index] <= time) {
                    mRow = index;
                } else {
                    break;
                }
            }
            // console.log("歌词正常更新")
            // this.lyric_last_state.row = mRow

        } else if (this.lyric_last_state.time > time) {
            // 被拉进度啦
            // let mRow = this.lyric_last_state.row;
            for (let index = this.lyric_last_state.row; index > 0; index--) {
                if (this.lyric_time[index] > time) {
                    mRow = index;
                } else {
                    break;
                }
            }

        } else {
            // 歌词没有变化.....
            return;
        }
        this.lyric_last_state.row = mRow;
        this.lyric_last_state.time = time;
        // console.log("歌词进度", this.lyric_last_state.row, time);
        store.state.playerState.playData.lrc_now_line_number = mRow;
        store.state.playerState.playData.lrc_now_line_str = store.state.playerState.playData.lrc_list[mRow];

    },
    /**
     * 初始化核心功能，运行周期监控器
     */
    initData() {
        if (store.state.playerState.playData.songId > 0) {
            mData.playId(store.state.playerState.playData.songId, store.state.playerState.playData.music_now_play_time, false)
            console.log("加载历史进度")
        }
        setInterval(function () {
            store.state.playerState.playData.music_now_play_time = player.currentTime
            store.state.playerState.playData.music_duration_time = player.duration
            mData.sync_lyric_time(player.currentTime)
        }, 500)
    },
    /**
     * 如果播放过程中遇到错误，则会触发该事件
     */
    event_play_intrupt() {
        Toast("歌曲流拉取失败!");
        //播放失败则转到下一首
        this.action_play_next();
    }


}

player.onplay = function () {
    // store.commit('mutationHandler', payload);
    // console.log("开始播放", player.src)
    store.state.playerState.playBackStatus = true
}
player.onpause = function () {
    store.state.playerState.playBackStatus = false

}
player.onended = function () {
    mData.action_play_next();
    // store.mutations.mutateSetPlayAction("","next");
}
player.onerror = function () {
    mData.event_play_intrupt();
}



export default mData
